package com.lwl.concurrency.synchr;

import java.util.concurrent.locks.ReentrantLock;

/**
 * tryLock()尝试获取锁,如果无法获取立即返回,
 * 也可以指定等待时间,在等待时间如果未获取到锁返回false
 *
 * @author liwenlong - 2018/3/27 17:36
 */
public class TryLockTest implements Runnable {

    public static ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            //if (lock.tryLock(5, TimeUnit.SECONDS)) {
            if (lock.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " get lock");
                Thread.sleep(6000);
            } else {
                System.out.println(Thread.currentThread().getName() + " get lock failed");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        TryLockTest tryLock = new TryLockTest();

        Thread t1 = new Thread(tryLock);
        Thread t2 = new Thread(tryLock);

        t1.start();
        t2.start();
    }


}
